﻿
//  ******************************************************************
//        /\ /|       @file       DateTimeNullableConvert.cs
//        \ V/        @brief      await 29
//        | "")       @author     Await, 285283010@qq.com
//        /  |
//       /  \\        @Modified   2023-10-13 11:30
//     *(__\_\        @Copyright  Copyright (c) 2023-10-13 11:30 , Await
//  ******************************************************************

using System.Text.Json;
using System.Text.Json.Serialization;

namespace AutomaticSubtitles.Service.Infrastructure.JsonConverter;

public class DateTimeNullableConvert: JsonConverter<DateTime?>
{
    private const string DateTimeFormat = "yyyy-MM-dd hh:mm:ss";

    public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.TryParse(reader.GetString(), out var dateTime) ? dateTime : default(DateTime?);
    }

    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value?.ToString(DateTimeFormat));
    }
}
